package com.cmh.mynfc;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.Ndef;
import android.os.Build;
import android.provider.Settings;
import android.util.Log;

public abstract class BaseNfcAActivity extends Activity {
    private static final String TAG = BaseNfcAActivity.class.getSimpleName();

    public NfcAdapter mNfcAdapter;
    public PendingIntent mPendingIntent;

    @Override
    protected void onStart() {
        super.onStart();
        mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
        if (mNfcAdapter == null) {
            return;
        } else {
            if (!mNfcAdapter.isEnabled()) {
                //到系统设置页面开启NFC开关
                Intent nfcSet = new Intent(Settings.ACTION_NFC_SETTINGS);
                startActivity(nfcSet);
            }
        }
        // 用于感应到NFC时启动该Activity
        // 这里建议将处理NFC的子类的launchMode设置成singleTop模式，这样感应到标签时就会回调onNewIntent，而不会重复打开页面
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            mPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()), PendingIntent.FLAG_MUTABLE);
        } else {
            mPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()), PendingIntent.FLAG_ONE_SHOT);
        }
//        mPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()), 0);
    }

    // 将Activity的launchMode设置成singleTop，这样当感应到NFC标签时不会重复打开页面，而是回调该方法
    @Override
    public void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        Log.e(TAG, "onNewIntent()");
        setIntent(intent);
    }

    @Override
    public void onResume() {
        Log.e(TAG, "onResume: ");
        super.onResume();
        // 设置当该页面处于前台时，NFC标签会直接交给该页面处理
        if (mNfcAdapter != null) {
            mNfcAdapter.enableForegroundDispatch(this, mPendingIntent, null, null);
            LoopCheckNfc();
        }
    }

    public void LoopCheckNfc() {
        Intent intent = getIntent();
        Tag detectedTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        Log.e(TAG, "detectedTag = " + detectedTag);
        if (detectedTag != null) {
            Log.e(TAG, "detectedTag != null");
            Ndef ndef = Ndef.get(detectedTag);
            new Thread(() -> {
                try {
                    if (ndef != null && (!ndef.isConnected())) {
                        Log.e(TAG, "ndef != null");
                        ndef.connect();
                        Log.e(TAG, "isConnected = " + ndef.isConnected());
                        NdefMessage ndefMessage = ndef.getNdefMessage();
                        if (ndefMessage != null) {
                            Log.e(TAG, "ndefMessage != null");
                            parseNdefMessage(ndefMessage);
                        } else {
                            Log.i(TAG, "run: ---消息为空");
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    try {
                        ndef.close();
                    } catch (Exception ignored) {
                    }
                }
            }).start();
        }
    }

    private String readText(NdefRecord record) {
        byte[] payload = record.getPayload();
        try {
            // 获取状态字节
            byte statusByte = payload[0];
            // 获取文本编码
            String textEncoding = ((statusByte & 0x80) == 0) ? "UTF-8" : "UTF-16";
            // 获取语言/地区编码
            int languageCodeLength = statusByte & 0x3F;
            // 解析文本
            String text = new String(payload, languageCodeLength + 1,
                    payload.length - languageCodeLength - 1,
                    textEncoding);
            return text;
        } catch (Exception e) {
            Log.e(TAG, "Error decoding text record: " + e.getMessage());
            return null;
        }
    }

    public abstract void onGetNfcText(String message);

    private void parseNdefMessage(NdefMessage ndefMessage) {
        for (NdefRecord ndefRecord : ndefMessage.getRecords()) {
            short tnf = ndefRecord.getTnf();
            Log.e(TAG, "tnf = " + tnf);
            if (tnf == NdefRecord.TNF_WELL_KNOWN) {
                String nfcMessage = readText(ndefRecord);
                Log.e(TAG, "nfcMessage = " + nfcMessage);
                if (nfcMessage != null) {
                    onGetNfcText(nfcMessage);
                    Log.e(TAG, "parseNdefMessage: =" + nfcMessage);
                }
            }
        }
    }

}
